<script setup>
import { reactive, ref } from 'vue'

// 表单对象
const ruleFormRef = ref()

// 表单内容绑定
const ruleForm = reactive({
    username: '',
    password: ''
})

// 表单校验规则
const rules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 5, message: '长度为3到5', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 10, message: '长度为6到10', trigger: 'blur' },
    ]
})

// 提交方法
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            ElMessage({
                message: '提交成功',
                grouping: true,
                type: 'success'
            })
        } else {
            console.log('error', fields)
            ElMessage({
                message: '校验失败',
                grouping: true,
                type: 'error'
            })
        }
    })
}

// 重置表单方法
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>

<template>
    <h1 text-center py-10 text-blue-500>表单提交</h1>
    <el-form class="w-1/3 m-auto" ref="ruleFormRef" :model="ruleForm" :rules="rules" status-icon>
        <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item>
            <div flex class="justify-between w-full pl-13">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </div>
        </el-form-item>
    </el-form>
</template>